package com.xxkj.drugtraceability.ui.main

import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.xxhis.drugtraceability.base.BaseViewModel
import com.xxkj.drugtraceability.App
import com.xxkj.drugtraceability.base.AppConfig
import com.xxkj.drugtraceability.bean.RoutBean
import com.xxkj.drugtraceability.net.Result
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * author: zhoujingjin
 * created on: 2024/9/10 9:04
 * description:
 */
class MainViewModel(application: Application, private val mainRepository: MainRepository):BaseViewModel(application) {
    var dataList = MutableLiveData<MutableList<RoutBean>>()
    var uiState = MutableLiveData<BaseUiModel<String>>()
    fun getRouters(){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                val routersResult = mainRepository.getRouters()
                if (routersResult is Result.Success){
                    try {
                        val show = routersResult.data.data.filter {
                            !it.hidden&& "1" ==it.meta.menuClassify
                         }
                        uiState.postValue(BaseUiModel(isRefresh = false))
                        dataList.postValue(show as MutableList<RoutBean>?)
                    } catch (e: Exception) {
                        uiState.postValue(BaseUiModel(isRefresh = false,showError = e.message))
                    }
                }else if (routersResult is Result.Error){
                    uiState.postValue(BaseUiModel(isRefresh = false,showError = routersResult.errorData))
                }
               val result = mainRepository.configKey("barcode")
                if (result is Result.Success){
                   AppConfig.barcode =  result.data.data.configValue
                }
            }
        }
    }
}